<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="lib/layui/css/layui.css">
    <style>
        .layui-form-pane .layui-form-radio, .layui-form-pane .layui-form-switch {
            margin-top: 6px;
            margin-left: 6px;
        }
    </style>
    <script src="lib/jquery-1.12.4.js"></script>
    <script src="lib/layui/layui.js"></script>
</head>
<body>
<div class="layui-container" style="margin-top: 30px">
    <form class="layui-form layui-form-pane" id="form" lay-filter="example" enctype="multipart/form-data">

        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">商品编号</label>
                <div class="layui-input-inline">
                    <input type="text" name="goodsId" id="goodsId" placeholder="请输入" autocomplete="off"
                           class="layui-input" lay-verify="goodsId" readonly>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">商品名称</label>
                <div class="layui-input-inline">
                    <input type="text" name="goodsName" id="goodsName" placeholder="请输入" autocomplete="off"
                           class="layui-input" lay-verify="goodsName">
                </div>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">安全库存</label>
                <div class="layui-input-inline">
                    <input type="text" name="safetyStock" id="safetyStock" lay-verify="safetyStock" placeholder="请输入" autocomplete="off"
                           class="layui-input">
                </div>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label">最大库存</label>
                <div class="layui-input-inline">
                    <input type="text" name="maxStock" id="maxStock" lay-verify="maxStock" placeholder="请输入" autocomplete="off"
                           class="layui-input">
                </div>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">购入价</label>
                <div class="layui-input-inline">
                    <input type="text" name="purchasePrice" id="purchasePrice" lay-verify="purchasePrice" placeholder="请输入" autocomplete="off"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">零售价</label>
                <div class="layui-input-inline">
                    <input type="text" name="salesPrice" id="salesPrice" lay-verify="salesPrice" placeholder="请输入" autocomplete="off"
                           class="layui-input">
                </div>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">规格选择</label>
                <div class="layui-input-block">
                    <input type="radio" name="spec" value="single" title="单规格" checked="" lay-filter="spec">
                    <input type="radio" name="spec" value="multi" title="多规格" lay-filter="spec">
                </div>
            </div>
            <div class="layui-inline" id="s">
                <label class="layui-form-label">单规格</label>
                <div class="layui-input-inline" id="a">
                    <select name="s_modules" lay-verify="required" lay-search="" lay-filter="singleSpec" id="singleSpec">
                        <option value="">选择或搜索选择</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline" id="m" style="display: none;">
                <label class="layui-form-label">多规格选择</label>
                <div class="layui-input-inline">
                    <select name="m_modules" lay-verify="" lay-search="" lay-filter="multiSpec" id="multiSpec">
                        <option value="">选择或搜索选择</option>
                    </select>
                </div>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">助记符</label>
                <div class="layui-input-inline">
                    <input type="text" name="remark" id="remark" lay-verify="remark" placeholder="请输入" autocomplete="off"
                           class="layui-input">
                </div>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">商品描述</label>
                <div class="layui-input-block">
                    <textarea placeholder="请输入内容" id="discription" class="layui-textarea" name="discription"></textarea>
                </div>
            </div>

            <div class="layui-inline">
                <span id="i"><img src="" alt="" id="img" style='width: 100px;height: 100px'></span>
                <input type="file" value=""  id="fileName" name="file" lay-verify="fileName">
                <p style="color: red" id="t2">* 请选择大小不超过1MB的图片，格式为&nbsp; .jpg&nbsp;|&nbsp;.jpeg&nbsp;|&nbsp;.png&nbsp;|&nbsp;.pneg格式</p>
                <!--<div class="layui-upload">-->
                    <!--<button type="button" class="layui-btn" id="test1" name="fileName">上传图片</button>-->
                    <!--<div class="layui-upload-list">-->
                        <!--<img class="layui-upload-img" id="demo1" lay-verify="fileName">-->
                        <!--<p id="demoText"></p>-->
                    <!--</div>-->
                <!--</div>-->
            </div>
        </div>

        <div class="layui-form-item" style="float: right">
            <div class="layui-input-inline">
                <button type="submit" class="layui-btn layui-layer-btn0" lay-submit="" lay-filter="save" id="save">保存</button>
                <button class="layui-btn layui-btn-primary" onclick="cancel()">取消</button>
            </div>
        </div>
    </form>
</div>

</body>

<script>
    layui.use(['form','upload'], function () {
        var form = layui.form;
        var $ = layui.jquery
         ,upload = layui.upload;

        form.on('radio(spec)', function(data) {
            if (data.value == 'single') {
                $("#s").show();
                $("#m").hide();
                $("select[name='m_modules']").removeAttr("lay-verify");
                $("select[name='s_modules']").attr("lay-verify","required");
                //console.log(data.value); //被点击的radio的value值
            } else if (data.value == 'multi') {
                $("#s").hide();
                $("#m").show();
                $("select[name='m_modules']").attr("lay-verify","required");
                $("select[name='s_modules']").removeAttr("lay-verify");
                //console.log(data.value); //被点击的radio的value值
            }
        });

        $.post('xp/goods/singleSpec',{},function(data){
            if(data.obj !=null){
                var $html = "";
                $.each(data.obj,function(index,item){
                    $html +="<option value="+item.specificationId+">"+item.specificationName+"</option>"
                });
                $("select[name='s_modules']").append($html);
                form.render('select');
            }
        });

        $.post('xp/goods/multiSpec',{},function(data){
            if(data.obj !=null){
                var $html = "";
                $.each(data.obj,function(index,item){
                    $html +="<option value="+item.specificationId+">"+item.specificationName+"</option>"
                });
                $("select[name='m_modules']").append($html);
                form.render('select');
            }
        });

        $.post('xp/goods/getNew',{},function (data) {
           if(data.obj>0){
               $("#goodsId").val(data.obj);
           }
        });

        function getObjectURL(file) {
            var url = null ;
            if (window.URL!=undefined) { // mozilla(firefox)
                url = window.URL.createObjectURL(file) ;
            } else if (window.webkitURL!=undefined) { // webkit or chrome
                url = window.webkitURL.createObjectURL(file) ;
            }
            return url ;
        }
        var file = $("#fileName");
        file.on("change",function(){
            var objUrl = getObjectURL(this.files[0]) ; //获取图片的路径，该路径不是图片在本地的路径
            if (objUrl) {
                $("#img").attr("src", objUrl) ; //将图片路径存入src中，显示出图片
            }

        });

        form.verify({
            goodsId: function(value){
                if(!value){
                    return '请输入商品编号';
                }
                var message = '';
                $.ajax({
                    url : 'xp/goods/getGoodsById',
                    data: {'goodsId': value},
                    type: 'post',
                    async: false,
                    dataType:'json',
                    success: function (data) {
                        if(data.msg==="success"){
                            message = ''
                        }else{
                            message= '编号已被使用，请重新输入'
                        }
                    },
                    error: function () {
                        return false;
                    }
                });
                return message;
            },
            maxStock: function(value){
                var reg = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
                if(!value){
                    return '请输入最大库存';
                }else if(!reg.test(value)){
                    return '请输入正确的库存';
                }
            },
            safetyStock: function(value){
                var reg = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
                if(!value){
                    return '请输入安全库存';
                }else if(!reg.test(value)){
                    return '请输入正确的库存';
                }
            },
            remark: function(value){
                if(!value){
                    return '请输入商品助记符';
                }
            },
            goodsName: function (value) {
                if(!value){
                    return '请输入商品名称';
                }
                var message = '';
                $.ajax({
                    url : 'xp/goods/getGoodsByName',
                    data: {'goodsName': value},
                    type: 'post',
                    async: false,
                    dataType:'json',
                    success: function (data) {
                        if(data.msg==="success"){
                            message = ''
                        }else{
                            message= '已被使用'
                        }
                    },
                    error: function () {
                        return false;
                    }
                });
                return message;
            },
            purchasePrice: function (value) {
                var reg = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
                if(!reg.test(value)){
                    return '请输入正确的金额'
                }
            },
            salesPrice: function (value) {
                var reg = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
                if(!reg.test(value)){
                    return '请输入正确的金额'
                }
            },
            fileName: function (value) {
                var animateimg = $("#fileName").val();  //获取上传的图片名 带//
                console.log(animateimg);
                if(!animateimg ){
                    return ''
                }else {
                    var imgarr=animateimg.split('\\');      //分割
                    var myimg=imgarr[imgarr.length-1]; //去掉 // 获取图片名
                    var houzui = myimg.lastIndexOf('.'); //获取 . 出现的位置
                    var ext = myimg.substring(houzui, myimg.length).toUpperCase();  //切割 . 获取文件后缀

                    //var files = $('#fileName').get(0).files[0]; //获取上传的文件
                    var fileSize = $("#fileName")[0].files[0].size;          //获取上传的文件大小
                    var maxSize = 1048576;              //最大1MB
                    if(ext !='.PNG' && ext !='.GIF' && ext !='.JPG' && ext !='.JPEG' && ext !='.BMP'){
                        return '文件类型错误，请选择图片上传'
                    }else if(parseInt(fileSize) >= parseInt(maxSize)) {
                        return '图片过大，请重新选择'
                    }
                }
            }

        });

        //表单取值
        layui.$('#LAY-component-form-getval').on('click', function(){
            var data = form.val('example');
            alert(JSON.stringify(data));
        });
        //监听提交
        form.on('submit(save)', function(data) {
            console.log(data.field);

            var form = document.getElementById("form");//获取页面已有的form表单
            var formData = new FormData(form);//用表单来初始化
            //formData.append("fileName",document.getElementById("fileName").files[0]);
            $.ajax({
                url: 'xp/goods/add',
                data: formData,
                dataType: 'json',
                type: "post",
                layerIndex: -1,
                cache : false,
                contentType : false,
                processData: false,
                success: function (data) {
                    if(data.addGoods.successful===true && data.addGoodsInfo.successful===true){
                        parent.layer.msg("新增商品成功",{icon:1});
                    }
                    //console.log(1);
                },
                complete: function () {
                    parent.layer.closeAll('iframe'); //关闭所有的iframe层
                }
            });
            return false;
        });

    });
    function cancel() {
        $('#save').attr('disabled','disabled');
        parent.layer.closeAll('iframe'); //关闭所有的iframe层

        // var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        // parent.layer.close(index); //再执行关闭
    }

</script>
</html>